<template>
  <el-form
    ref="storeForm"
    :model="storeForm"
    :rules="rules"
    label-width="130px"
    class="demo-storeForm"
  >
    <el-form-item label="销售分类：" prop="categoryId">
      <el-select
        v-model="storeForm.categoryId"
        placeholder="请选择销售分类："
        @change="change"
      >
        <el-option
          v-for="item in saleData"
          :key="item.id"
          :label="item.categoryName"
          :value="item.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="店铺名称：" prop="sellerName">
      <el-input
        v-model="storeForm.sellerName"
        maxlength="30"
        @focus="hideErrMsg('sellerName')"
      />
    </el-form-item>
    <el-form-item label="店铺销售简介：" prop="sellIntroduct">
      <el-input
        v-model="storeForm.sellIntroduct"
        type="textarea"
        maxlength="500"
        :rows="2"
        show-word-limit
        style="height:145px;"
        @focus="hideErrMsg('sellIntroduct')"
      />
    </el-form-item>
    <el-form-item label="业务联系人：" prop="salesman">
      <el-input
        v-model="storeForm.salesman"
        maxlength="30"
        @focus="hideErrMsg('salesman')"
      />
    </el-form-item>
    <el-form-item label="联系电话：" prop="contactPhone">
      <el-input
        v-model="storeForm.contactPhone"
        maxlength="11"
        @focus="hideErrMsg('contactPhone')"
      />
    </el-form-item>
    <el-form-item label="短信验证码：" prop="code">
      <el-input
        v-model="storeForm.code"
        maxlength="6"
        @focus="hideErrMsg('code')"
      >
        <span slot="append" class="authentication" :disabled="!canSend" @click="getCode" v-text="content">邮箱验证码</span>
      </el-input>
    </el-form-item>
    <el-form-item label="办公电话：" prop="emergcyPhone">
      <el-input
        v-model="storeForm.emergcyPhone"
        maxlength="50"
        @focus="hideErrMsg('emergcyPhone')"
      />
      <div class="phone-tips">提示：办公电话可输入多个手机号或座机，输入多个电话时使用逗号“，”连接，如：13800138000，020-38373230</div>
    </el-form-item>
    <el-form-item class="step">
      <div class="common last" @click="last">返回上一步</div>
      <div class="common next" @click="next">下一步</div>
    </el-form-item>
  </el-form>
</template>

<script>
import { countdown } from '@/util/countdown'
import { listCategoryInfo, checkSellerName, code, stepTwo } from '@/api/join'
import { phoneReg, phoneCodeReg, phoneOrFixedReg, charReg } from '@/js/regex'
export default {
  props: {
    storeForm: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      // 完善公司信息
      rules: {
        categoryId: [
          { required: true, message: '请选择销售分类', trigger: 'change' }
        ],
        sellerName: [
          { required: true, validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('请输入店铺名称'))
              return
            }
            if (value && value.length > 30) {
              callback(new Error('店铺名称不能超过30位'))
              return
            }
            if (charReg.test(value)) {
              callback(new Error('店铺名称不能含有非法字符@#$%^&*'))
              return
            }
            checkSellerName(value).then(res => {
              if (!res.data) {
                callback(new Error(`"${value}" 已被占用`))
              } else {
                callback()
              }
            })
          }, trigger: 'blur' }
        ],
        sellIntroduct: [
          { required: true, message: '请输入店铺销售简介', trigger: 'blur' },
          { max: 500, message: '店铺销售简介不能超过500位', trigger: 'blur' }
        ],
        salesman: [
          { required: true, message: '请输入业务联系人', trigger: 'blur' },
          { max: 20, message: '业务联系人姓名不能超过30位', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: phoneReg, message: '联系电话格式不正确', trigger: 'blur' }
        ],
        code: [
          { required: true, validator: (rule, value, callback) => {
            if (!this.storeForm.contactPhone) {
              callback(new Error('请先输入联系电话'))
              return
            }
            if (!phoneReg.test(this.storeForm.contactPhone)) {
              callback(new Error('联系电话格式不正确'))
              return
            }
            if (!this.send) {
              callback(new Error('请先发送验证码'))
              return
            }
            if (!value) {
              callback(new Error('请输入手机验证码'))
              return
            }
            if (!phoneCodeReg.test(value)) {
              callback(new Error('手机验证码只能为六位纯数字'))
              return
            }
            callback()
          }, trigger: 'blur' }
        ],
        emergcyPhone: [
          { required: true, validator: (rule, value, callback) => {
            if (value) {
              if (value.indexOf('，') !== -1) {
                value = value.replace('，', ',')
                this.storeForm.emergcyPhone = value
              }
              const arr = value.split(',')
              let message
              for (let i = 0; i < arr.length; i++) {
                if (!phoneOrFixedReg.test(arr[i])) {
                  message = '紧急联系电话格式不正确'
                  break
                }
                if (this.storeForm.contactPhone === arr[i]) {
                  message = '紧急联系电话不能与联系电话一致'
                  break
                }
              }
              if (message) {
                callback(new Error(message))
                return
              }
              if (new Set(arr).size < arr.length) {
                message = '紧急联系电话不能有重复'
                callback(new Error(message))
                return
              }
            }
            callback()
          }, trigger: 'blur' }
        ]
      },
      saleData: [],
      content: '发送验证码', // 按钮里显示的内容
      totalTime: 60,
      canSend: true,
      send: false,
      clock: undefined,
      codeKey: undefined,
      reBack: true
    }
  },
  mounted() {
    listCategoryInfo().then(res => {
      this.saleData = res.data
    })
  },
  methods: {
    change(id) {
      this.storeForm.categoryName = this.saleData.filter(i => i.id === id)[0].categoryName
    },
    hideErrMsg(progName) {
      this.$refs.storeForm.clearValidate(progName)
    },
    // 点击上一步
    last() {
      this.$emit('lastSecond', 2)
    },
    // 点击下一步
    next() {
      this.$refs.storeForm.validate(valid => {
        if (valid) {
          if (!this.send) {
            this.$message.info('请先发送验证码')
            return
          }
          const data = JSON.parse(JSON.stringify(this.storeForm))
          delete data.code
          const headers = {
            codeKey: this.codeKey,
            code: this.storeForm.code
          }
          this.submit = true
          stepTwo(data, sessionStorage.getItem('uuid'), headers).then(res => {
            if (res.data) {
              this.submit = false
              this.reBack = false
              // this.$router.push('/join-apply-third-submit-success')
              this.$emit('nextFourth', 4, this.storeForm)
            } else {
              this.submit = false
              this.$message.error('提交失败,请稍后重试')
            }
          }).catch(res => {
            this.submit = false
            this.$message.error(res.data)
          })
        }
      })
    },
    // 发送验证码
    getCode() {
      this.$refs.storeForm.validateField('contactPhone', phoneError => {
        if (!phoneError) {
          if (!this.canSend) {
            return
          }
          countdown(this)
          this.$refs.storeForm.clearValidate('code')
          code(sessionStorage.getItem('uuid'), this.storeForm.contactPhone).then(response => {
            if (response.data) {
              this.codeKey = response.message
              this.send = true
            }
          }).catch(res => {
            // Toast(res.data)
            this.send = false
            window.clearInterval(this.clock)
            this.content = '重新发送验证码'
            this.totalTime = 60
            this.canSend = true
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.authentication:hover{
  cursor: pointer;
}
  ::v-deep .el-textarea__inner {
          height: 145px!important;
        }
.step {
  margin-top: 38px;
  ::v-deep .el-form-item__content {
      width: 400px;
      display: flex;
      flex-direction: column;
    justify-content: center;
    align-items: center;
    }

  .common {
      width: 80px;
      height: 30px;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .common:hover {
      cursor: pointer;
    }
    .next {
       width: 100%;
      color: #ffffff;
      background-color: #ff3b30;
      height: 42px;
    }
    .last {
      width: 100%;
      color: #6b6b6b;
      height: 42px;
      background-color: #e5e5e5;
      margin-bottom: 15px;
    }
}
.phone-tips{
  color: #fd2f1c;
}
</style>
